﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Zvezda.FSO2.DB;

namespace FSO
{
    public partial class FormInvoiceIn : Form, InterfaceObjDeleteableForm
    {

        private DataSetFSO.INVOICE_INRow _rowInvoiceIn;
        private bool _rowIsNew;
		public bool AllowSave;
        public FormInvoiceIn()
        {
            InitializeComponent();
            _rowIsNew = true;
            
            //Создаем новый входящий счет
            _rowInvoiceIn = dataSetFSO1.INVOICE_IN.NewINVOICE_INRow();
            //Полю "Дата" по умолчанию присваиваем сегодняшнее число
            _rowInvoiceIn.DATE = DateTime.Now.Date;
            _rowInvoiceIn.REG_NUMBER = (int) invoicE_INTableAdapter1.GetInvInRegNum();
            dataSetFSO1.INVOICE_IN.AddINVOICE_INRow(_rowInvoiceIn);

            //radDateTimePickerPlanPaymentDate.Text = "";
            //radDateTimePickerPlanPaymentDate.Value = DateTime.Now.Date;
            //radDateTimePickerPlanPaymentDate.NullDate = ;
        }

        // Может понадобится в будущем сооздавтать новую Форму с уже заранее известными параметрами
        //public FormInvoiceIn(DateTime time)
        //{
           
        //}

        public FormInvoiceIn(DataSetFSO.INVOICE_INRow row)
        {
            InitializeComponent();
            _rowIsNew = false;

            invoicE_INTableAdapter1.FillByID(dataSetFSO1.INVOICE_IN, row.ID);
            _rowInvoiceIn = dataSetFSO1.INVOICE_IN.FindByID(row.ID);

            this.Text = "Счет № " + _rowInvoiceIn.REG_NUMBER;
        }



        #region InterfaceObjDeleteableForm Members

        public int Delete()
        {
            //Если в PAY_OUT_ON_INV_IN добавлена новая запись, но не было сохранения в базу, то при удалении платежа будет ошибка
            //поэтому надо убрать все вновь добавленные строки
            //dataSetFSO1.PAY_OUT_ON_INV_IN.RejectChanges();

            //foreach (DataSetFSO.PAY_OUT_ON_INV_INRow row in dataSetFSO1.PAY_OUT_ON_INV_IN.Rows)
            //{
            //    row.Delete();
            //}

            //Тоже самое для пунктов

            //dataSetFSO1.INVOICE_IN_ITEM.RejectChanges();

            //foreach (DataSetFSO.INVOICE_IN_ITEMRow row in dataSetFSO1.INVOICE_IN_ITEM.Rows)
            //{
            //    row.Delete();
            //}

            _rowInvoiceIn.Delete();

            //paY_OUT_ON_INV_INTableAdapter1.Update(dataSetFSO1.PAY_OUT_ON_INV_IN);
            //invoicE_IN_ITEMTableAdapter1.Update(dataSetFSO1.INVOICE_IN_ITEM);
            invoicE_INTableAdapter1.Update(_rowInvoiceIn);

            this.Close();

            return 0;
        }

        #endregion

        #region IntefaceObjectForm Members

        public int Save()
        {
            //Такое значение возвратится, если сохранение не произошло
            int nRowsUpdatedCount = -1;

            //if (_rowInvoiceIn.IsNUMBERNull())
            //{
            //    MessageBox.Show(this, "Не заполнено обязательное поле \"Номер\".\nИзменения не будут сохранены", "Обязательное поле", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //}
            //else
            //{
                nRowsUpdatedCount = invoicE_INTableAdapter1.Update(_rowInvoiceIn);

                foreach (DataSetFSO.PAY_OUT_ON_INV_INRow row in dataSetFSO1.PAY_OUT_ON_INV_IN.Rows)
                {
                    if (row.RowState == DataRowState.Added)
                        row.INVOICE_IN_ID = _rowInvoiceIn.ID;
                }
                paY_OUT_ON_INV_INTableAdapter1.Update(dataSetFSO1.PAY_OUT_ON_INV_IN);

                foreach (DataSetFSO.INVOICE_IN_ITEMRow row in dataSetFSO1.INVOICE_IN_ITEM)
                {
                    if (row.RowState == DataRowState.Added)
                        row.INVOICE_IN_ID = _rowInvoiceIn.ID;
                }

                invoicE_IN_ITEMTableAdapter1.Update(dataSetFSO1.INVOICE_IN_ITEM);

                _rowIsNew = false;
                this.RefreshForm();
            //}

            return nRowsUpdatedCount;
        }

        public string FormName
        {
            get
            {
                string returnString = "Invoice_In_";

                if (_rowIsNew)
                {
                    returnString = returnString + DateTime.Now;
                }
                else
                {
                    returnString = returnString +_rowInvoiceIn.ID;
                }

                return returnString;
            }
        }

        public int RefreshForm()
        {
            int result = 0;
            //Валюта
            nsI_CURRENCYTableAdapter1.Fill(dataSetFSO1.NSI_CURRENCY);
            radDropDownListCurrency.Items.Clear();
            foreach (DataSetFSO.NSI_CURRENCYRow row in dataSetFSO1.NSI_CURRENCY.Rows)
            {
                radDropDownListCurrency.Items.Add(new RadListDataItem() { Text = row.SHORT_NAME, Value = row.ID });
            }

            //Источник финансирования
            nsI_FINANCE_RESOURCETableAdapter1.Fill(dataSetFSO1.NSI_FINANCE_RESOURCE);
            radDropDownListFinResource.Items.Clear();
            foreach (DataSetFSO.NSI_FINANCE_RESOURCERow row in dataSetFSO1.NSI_FINANCE_RESOURCE.Rows)
            {
                radDropDownListFinResource.Items.Add(new RadListDataItem() { Text = row.NAME, Value = row.ID });
            }

            //Статья расходов
            nsI_EXPENSE_ITEMTableAdapter1.Fill(dataSetFSO1.NSI_EXPENSE_ITEM);
            radDropDownListExpenseItem.Items.Clear();
            foreach (DataSetFSO.NSI_EXPENSE_ITEMRow row in dataSetFSO1.NSI_EXPENSE_ITEM.Rows)
            {
                radDropDownListExpenseItem.Items.Add(new RadListDataItem() { Text = row.NAME, Value = row.ID });
            }

            //Направление
            nsI_TYPE_OF_ACTIVITYTableAdapter1.Fill(dataSetFSO1.NSI_TYPE_OF_ACTIVITY);
            radDropDownListActivityType.Items.Clear();
            foreach (DataSetFSO.NSI_TYPE_OF_ACTIVITYRow row in dataSetFSO1.NSI_TYPE_OF_ACTIVITY.Rows)
            {
                radDropDownListActivityType.Items.Add(new RadListDataItem() { Text = row.NAME, Value = row.ID });
            }

            //указание к оплате
            nsI_PAY_DIRECTTableAdapter1.Fill(dataSetFSO1.NSI_PAY_DIRECT);
            radDropDownListPayDirect.Items.Clear();
            foreach (DataSetFSO.NSI_PAY_DIRECTRow row in dataSetFSO1.NSI_PAY_DIRECT.Rows)
            {
                radDropDownListPayDirect.Items.Add(new RadListDataItem() { Text = row.NAME, Value = row.ID });
            }

            //Платежи
            paY_OUT_ON_INV_INTableAdapter1.FillByInvInID(dataSetFSO1.PAY_OUT_ON_INV_IN, _rowInvoiceIn.ID);

            //Пункты
            invoicE_IN_ITEMTableAdapter1.FillByInvInId(dataSetFSO1.INVOICE_IN_ITEM, _rowInvoiceIn.ID);

            
            //Можно сделать кнопки очистки значений
            this.BindControls();

            return result;
        }

        #endregion

        private void FormInvoiceIn_Load(object sender, EventArgs e)
        {
            
            // Пункты
            GridViewTextBoxColumn colMaterial = new GridViewTextBoxColumn("NSI_MATERIAL_NAME",dataSetFSO1.INVOICE_IN_ITEM.NSI_MATERIAL_NAMEColumn.ColumnName);            
            colMaterial.HeaderText = "Материал";
            colMaterial.ReadOnly = true;
            GridViewTextBoxColumn colComments = new GridViewTextBoxColumn("COMMEMNTS", dataSetFSO1.INVOICE_IN_ITEM.COMMENTSColumn.ColumnName);
            colComments.HeaderText = "Комментарии";
            GridViewDecimalColumn colQuantity = new GridViewDecimalColumn("QUANTITY", dataSetFSO1.INVOICE_IN_ITEM.QUANTITYColumn.ColumnName);
            colQuantity.HeaderText = "Количество";
            colQuantity.DecimalPlaces = 0;
            colQuantity.Minimum = 0;           
            GridViewTextBoxColumn colMeter = new GridViewTextBoxColumn("NSI_UNIT_ID", dataSetFSO1.INVOICE_IN_ITEM.NSI_METER_NAMEColumn.ColumnName);
            colMeter.HeaderText = "Ед.";
            colMeter.ReadOnly = true;

            radGridViewMaterials.MasterTemplate.Columns.Clear();
            radGridViewMaterials.MasterTemplate.Columns.Add(colMaterial);
            radGridViewMaterials.MasterTemplate.Columns.Add(colComments);
            radGridViewMaterials.MasterTemplate.Columns.Add(colQuantity);
            radGridViewMaterials.MasterTemplate.Columns.Add(colMeter);

            radGridViewMaterials.DataSource = dataSetFSO1.INVOICE_IN_ITEM;
            
            
            //Платежи
            GridViewTextBoxColumn colPayNum = new GridViewTextBoxColumn("PAYMENT_OUT_NUMBER", dataSetFSO1.PAY_OUT_ON_INV_IN.PAY_NUMBERColumn.ColumnName);
            colPayNum.HeaderText = "№";
            colPayNum.ReadOnly = true;
            GridViewDecimalColumn colSumRub = new GridViewDecimalColumn("SUM_RUB", dataSetFSO1.PAY_OUT_ON_INV_IN.SUM_RUBColumn.ColumnName);
            colSumRub.HeaderText = "Сумма списания(руб.)";
            colSumRub.Minimum = 0;
            colSumRub.FormatString = "{0:N2}";
            GridViewDecimalColumn colSumCur = new GridViewDecimalColumn("SUM_CUR", dataSetFSO1.PAY_OUT_ON_INV_IN.SUM_CURColumn.ColumnName);
            colSumCur.HeaderText = "Сумма списания(" + radDropDownListCurrency.SelectedText + ")";
            colSumCur.Minimum = 0;
            colSumCur.FormatString = "{0:N2}";
            GridViewDateTimeColumn colPayDate = new GridViewDateTimeColumn("DATE", dataSetFSO1.PAY_OUT_ON_INV_IN.PAY_DATEColumn.ColumnName);
            colPayDate.HeaderText = "Дата платежа";
            colPayDate.FormatString = "{0:d}";
            colPayDate.ReadOnly = true;


            radGridViewPayments.MasterTemplate.Columns.Clear();
            radGridViewPayments.MasterTemplate.Columns.Add(colPayNum);
            radGridViewPayments.MasterTemplate.Columns.Add(colSumRub);
            radGridViewPayments.MasterTemplate.Columns.Add(colSumCur);
            radGridViewPayments.MasterTemplate.Columns.Add(colPayDate);

            radGridViewPayments.DataSource = dataSetFSO1.PAY_OUT_ON_INV_IN;

            dataSetFSO1.PAY_OUT_ON_INV_IN.ColumnChanged += new DataColumnChangeEventHandler(PAY_OUT_ON_INV_IN_ColumnChanged);

            this.RefreshForm();
        }

        void PAY_OUT_ON_INV_IN_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            DataSetFSO.PAY_OUT_ON_INV_INRow poi = (DataSetFSO.PAY_OUT_ON_INV_INRow)e.Row;
            string curName = radDropDownListCurrency.Text;
            //Если изменили валютную ячейку
            if (e.Column.ColumnName == dataSetFSO1.PAY_OUT_ON_INV_IN.SUM_CURColumn.ColumnName)
            {
                if (Decimal.Round(this.GetRest(), 2) < 0)
                {
                    MessageBox.Show("Превышена сумма счета!\nПроверьте правильность введенных данных ");

                    //Приравниваем подходящее значение ячейке ()
                    poi.SUM_CUR = poi.SUM_CUR + this.GetRest();
                }
                //пересчитываем соседнюю ячейку
                decimal rate = FormHelper.GetRate(curName, poi.PAY_DATE);

                if (rate > 0 && poi.SUM_RUB != poi.SUM_CUR * rate)
                {
                    poi.SUM_RUB = poi.SUM_CUR * rate;
                }

            }
            //если изменили рублевую ячейку
            else if (e.Column.ColumnName == dataSetFSO1.PAY_OUT_ON_INV_IN.SUM_RUBColumn.ColumnName)
            {
                //Высчитываем остаток
                decimal rest = FormPaymentOut.GetRestWithoutItem(poi.PAYMENT_OUT_ID, poi.ID) - (poi.IsSUM_RUBNull() ? 0 : poi.SUM_RUB);

                if (Decimal.Round(rest, 2) < 0)
                {
                    MessageBox.Show("Превышена сумма платежа!\n Проверьте правильность введенных данных ");

                    //Приравниваем подходящее значение ячейке ()
                    poi.SUM_RUB = poi.SUM_RUB + rest;

                    //пересчитываем соседнюю ячейку
                }
                decimal rate = FormHelper.GetRate(curName, poi.PAY_DATE);
                if (rate > 0 && poi.SUM_CUR != poi.SUM_RUB / rate)
                {
                    poi.SUM_CUR = poi.SUM_RUB / rate;
                }

            }
        }

        private void BindControls()
        { 
            //Код счета
            radLabelCode.DataBindings.Clear();
            radLabelCode.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.REG_NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Местонахождение
            radTextBoxArea.DataBindings.Clear();
            radTextBoxArea.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.AREALColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Номер
            radTextBoxNumber.DataBindings.Clear();
            radTextBoxNumber.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Дата
            radDateTimePickerDate.DataBindings.Clear();
            radDateTimePickerDate.DataBindings.Add("Value", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Номер договора
            radTextBoxContractNumber.DataBindings.Clear();
            radTextBoxContractNumber.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.CONTRACT_NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Сумма в валюте
            radMaskedEditBoxSumCUR.DataBindings.Clear();
            radMaskedEditBoxSumCUR.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.SUMColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged, 0, "N2");

            radDropDownListCurrency.DataBindings.Clear();
            radDropDownListCurrency.DataBindings.Add("SelectedValue", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.NSI_CURRENCY_IDColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            

            //Направление
            radDropDownListActivityType.DataBindings.Clear();
            radDropDownListActivityType.DataBindings.Add("SelectedValue", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.NSI_TYPE_OF_ACTIVITY_IDColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //№ папки
            radDropDownListFolderN.DataBindings.Clear();
            radDropDownListFolderN.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.N_FOLDERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Город
            radTextBoxCity.DataBindings.Clear();
            radTextBoxCity.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.CITYColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Организация
           
            radLabelOrganizationName.DataBindings.Clear();
            radLabelOrganizationName.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.NSI_ORG_NAMEColumn.ColumnName, true, DataSourceUpdateMode.Never, "<Не указана>");
           
            
            // Договор (тема) и дата
          
            radLabelContractName.DataBindings.Clear();
            radLabelContractName.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.CONTRACT_C_NUMBERColumn.ColumnName, true, DataSourceUpdateMode.Never, "<Не указан>");
            radLabelContractDate.DataBindings.Clear();
            radLabelContractDate.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.CONTRACT_C_START_DAYColumn.ColumnName, true, DataSourceUpdateMode.Never, "<Не указана>");
          
            

            //Состояние
            radDropDownListState.DataBindings.Clear();
            radDropDownListState.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.STATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            // Планируемая дата оплаты
            radDateTimePickerPlanPaymentDate.DataBindings.Clear();
            radDateTimePickerPlanPaymentDate.DataBindings.Add("Value", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.PLAN_PAY_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Указание к оплате
            radDropDownListPayDirect.DataBindings.Clear();
            radDropDownListPayDirect.DataBindings.Add("SelectedValue", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.NSI_PAY_DIRECT_IDColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Источник финансирования
            radDropDownListFinResource.DataBindings.Clear();
            radDropDownListFinResource.DataBindings.Add("SelectedValue", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.NSI_FINANCE_RESOURCE_IDColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Статья расходов
            radDropDownListExpenseItem.DataBindings.Clear();
            radDropDownListExpenseItem.DataBindings.Add("SelectedValue", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.NSI_EXPENSE_ITEM_IDColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Комментарии
            radTextBoxDescription.DataBindings.Clear();
            radTextBoxDescription.DataBindings.Add("Text", _rowInvoiceIn, dataSetFSO1.INVOICE_IN.DESCRIPTIONColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Название колонки "Сумма в валюте" в таблице платежей
            radGridViewPayments.Columns["SUM_CUR"].HeaderText = "Сумма списания(" + radDropDownListCurrency.SelectedText + ")";

            //Остаток счета
            if (_rowInvoiceIn.IsSUMNull())
            {
                radLabelRestCurrency.Text = "Не задана сумма счета!";
                radLabelRestRub.Text = "";

            }
            else
            {
                decimal rest = this.GetRest();
                string curencyName = radDropDownListCurrency.SelectedText;
                decimal rate = (decimal) nsI_EXCHANGE_RATETableAdapter1.getRate(curencyName, DateTime.Now.Date);

                radLabelRestCurrency.Text = Decimal.Round(rest,2) + " " + curencyName;

                if (rate == 0)
                {
                    radLabelRestRub.Text = "Не задан курс на текущую дату!";
                }
                else
                {
                    radLabelRestRub.Text = Decimal.Round(rest * rate, 2) + " руб.";
                }
            }
            

        }

        private void FormInvoiceIn_FormClosing(object sender, FormClosingEventArgs e)
        {

			if (!AllowSave)
				return;
            if (_rowInvoiceIn.RowState == DataRowState.Added || _rowInvoiceIn.RowState == DataRowState.Modified || dataSetFSO1.PAY_OUT_ON_INV_IN.GetChanges() !=null || dataSetFSO1.INVOICE_IN_ITEM.GetChanges() != null)
            {
                DialogResult result = MessageBox.Show(this, "Были внесены изменения. Сохранить?", "Сохранить изменения?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    int SaveResult = this.Save();

                    if (SaveResult == -1)
                    {
                        e.Cancel = true; 
                    }
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else
                {
                    _rowInvoiceIn.RejectChanges();
                }

            }
               
        }

        private void radLabelOrganizationName_DoubleClick(object sender, EventArgs e)
        {
            if (_rowInvoiceIn.IsNSI_ORGANIZATION_IDNull())
            {
                //DialogFormSelectOrganization form = new DialogFormSelectOrganization();
                DialogFormSelectObject form = new DialogFormSelectObject(ObjctTypeEnum.ORGANIZATION);
                if (form.ShowDialog() == DialogResult.OK && form.SelectedRow != null)
                {
                    DataSetFSO.NSI_ORGANIZATIONRow contractRow = (DataSetFSO.NSI_ORGANIZATIONRow)form.SelectedRow;

                    _rowInvoiceIn.NSI_ORGANIZATION_ID = contractRow.ID;
                    //заполняем город и названии организации из контракта
                    if (!contractRow.IsSHORT_NAMENull())
                        radLabelOrganizationName.Text = contractRow.SHORT_NAME;
                    if (!contractRow.IsCITYNull())
                        radTextBoxCity.Text = contractRow.CITY;
                }
            }
            else
            {
                FormNSIOrganization form = new FormNSIOrganization(nsI_ORGANIZATIONTableAdapter1.GetDataById(_rowInvoiceIn.NSI_ORGANIZATION_ID).FindByID(_rowInvoiceIn.NSI_ORGANIZATION_ID));
                if (!FormHelper.HasOpenedForm(form.FormName))
                {
                    form.MdiParent = FormHelper.MainForm;
                    form.Show();
                    form.Select();
                }
            }
        }

        private void radLabelContractName_DoubleClick(object sender, EventArgs e)
        {
            if (_rowInvoiceIn.IsNSI_CONTRACT_IDNull())
            {
                //DialogFormSelectContract form = new DialogFormSelectContract();
                DialogFormSelectObject form = new DialogFormSelectObject(ObjctTypeEnum.CONTRACT);
                if (form.ShowDialog() == DialogResult.OK && form.SelectedRow != null)
                {
                    DataSetFSO.CONTRACTRow contract = (DataSetFSO.CONTRACTRow)form.SelectedRow;
                    _rowInvoiceIn.NSI_CONTRACT_ID = contract.ID;
                    radLabelContractName.Text = contract.NUMBER;
                    radLabelContractDate.Text = contract.START_DATE.ToShortDateString();
                }
            }
            else
            {
                FormContract form = new FormContract(contractTableAdapter1.GetDataByID(_rowInvoiceIn.NSI_CONTRACT_ID).FindByID(_rowInvoiceIn.NSI_CONTRACT_ID));
                if (!FormHelper.HasOpenedForm(form.FormName))
                {
                    form.MdiParent = FormHelper.MainForm;
                    form.Show();
                    form.Select();
                }
            }
        }

        private void radButtonDetachOrganization_Click(object sender, EventArgs e)
        {
            _rowInvoiceIn.SetNSI_ORGANIZATION_IDNull();
            _rowInvoiceIn.SetNSI_ORG_NAMENull();
            radLabelOrganizationName.Text = "Не указана";
            radTextBoxCity.Text = "";
        }

        private void radButtonDetachContract_Click(object sender, EventArgs e)
        {
            _rowInvoiceIn.SetNSI_CONTRACT_IDNull();
            _rowInvoiceIn.SetCONTRACT_C_NUMBERNull();
            _rowInvoiceIn.SetCONTRACT_C_START_DAYNull();
            radLabelContractName.Text = "Не указан";
            radLabelContractDate.Text = "Не указана";
            radDropDownListActivityType.SelectedIndex = -1;
        }

        private void radButtonAddPay_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject form = new DialogFormSelectObject(ObjctTypeEnum.PAYMENT_OUT);
            if (form.ShowDialog() == DialogResult.OK)
            {
                foreach (GridViewRowInfo rowInf in form.SelectedRows)
                {
                    DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                    if (drv != null && drv.Row is DataSetFSO.PAYMENT_OUTRow)
                    {
                        DataSetFSO.PAYMENT_OUTRow payOutRow = drv.Row as DataSetFSO.PAYMENT_OUTRow;
                        int countLink = (int) paY_OUT_ON_INV_INTableAdapter1.IsPayOutLinked(payOutRow.ID);
                        //MessageBox.Show(countLink.ToString());
                        //Проверяем был ли добавлен платеж к счету
                        if ((from row in dataSetFSO1.PAY_OUT_ON_INV_IN select row.PAYMENT_OUT_ID).Contains(payOutRow.ID))
                        {
                            MessageBox.Show("Данный платеж уже был добавлен к счету!");
                        }
                        ////делаем связь 1 счет - много платежей, но на всякий случай оставим в базе возмоность связи много ко многому - вдруг им захочется, достаточно буде убрать if
                        else if(countLink > 0)
                        {
                            MessageBox.Show("Данный платеж уже был добавлен к другому счету!");
                        }
                        else
                        {
                            DataSetFSO.PAY_OUT_ON_INV_INRow rowOrig = dataSetFSO1.PAY_OUT_ON_INV_IN.NewPAY_OUT_ON_INV_INRow();
                            dataSetFSO1.PAY_OUT_ON_INV_IN.AddPAY_OUT_ON_INV_INRow(rowOrig);
                            //rowOrig.INVOICE_INRow = _rowInvoiceIn;
                            rowOrig.PAYMENT_OUT_ID = payOutRow.ID;
                            if (!payOutRow.IsNUMBERNull())
                                rowOrig.PAY_NUMBER = payOutRow.NUMBER;
                            if (!payOutRow.IsDATENull())
                                rowOrig.PAY_DATE = payOutRow.DATE;
                            rowOrig.SUM_RUB = payOutRow.SUM_RUB;
                        }
                    }
                }
            }          
        }

        private void radButtonAddMaterials_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject form = new DialogFormSelectObject(ObjctTypeEnum.NSI_MATERIAL);
            if (form.ShowDialog() == DialogResult.OK)
            {
                foreach (GridViewRowInfo rowInf in form.SelectedRows)
                {
                    DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                    if (drv != null && drv.Row is DataSetFSO.NSI_MATERIALRow)
                    {
                        DataSetFSO.NSI_MATERIALRow nsiMaterialRow = drv.Row as DataSetFSO.NSI_MATERIALRow;
                        DataSetFSO.INVOICE_IN_ITEMRow rowOrig = dataSetFSO1.INVOICE_IN_ITEM.NewINVOICE_IN_ITEMRow();
                        dataSetFSO1.INVOICE_IN_ITEM.AddINVOICE_IN_ITEMRow(rowOrig);
                        //rowOrig.PAYMENT_OUT_ID = _rowPayOut.ID;
                        rowOrig.NSI_MATERIAL_ID = nsiMaterialRow.ID;
                        //if (!nsiMaterialRow.IsNAMENull())
                        rowOrig.NSI_MATERIAL_NAME = nsiMaterialRow.NAME;
                        if (!nsiMaterialRow.IsNSI_METER_NAMENull())
                            rowOrig.NSI_METER_NAME = nsiMaterialRow.NSI_METER_NAME;
                    }
                }
            }        
        }

        //Свойство возвращает строку Payment_out, на основе выделенной строчки в таблице платежей
        public DataSetFSO.PAYMENT_OUTRow SelectedPayRow
        {
            get
            {
                DataSetFSO.PAY_OUT_ON_INV_INRow tmp;
                DataSetFSO.PAYMENT_OUTRow row;
                if (radGridViewPayments.SelectedRows.Count > 0)
                {
                    tmp = (DataSetFSO.PAY_OUT_ON_INV_INRow)(((DataRowView)(radGridViewPayments.SelectedRows.First()).DataBoundItem)).Row;
                    row = paymenT_OUTTableAdapter1.GetDataByID(tmp.PAYMENT_OUT_ID).FindByID(tmp.PAYMENT_OUT_ID);
                }
                else
                {
                    row = null;
                }
                return row;
            }
        }

        private void radGridViewPayments_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            DataSetFSO.PAYMENT_OUTRow payOutRow = this.SelectedPayRow;
            if (payOutRow != null)
            {

                FormPaymentOut formPayOut = new FormPaymentOut(payOutRow);
                if (!FormHelper.HasOpenedForm(formPayOut.FormName))
                {
                    formPayOut.MdiParent = FormHelper.MainForm;
                    formPayOut.Show();
                    formPayOut.Select();
                }

            }
        }

        /*//Пересчитывает знаечние ячейки по курсу на дату платежа
        private void radGridViewPayments_CellEndEdit(object sender, GridViewCellEventArgs e)
        {
            if (e.Column.Name == "SUM_CUR")
            {
                DateTime payDate = ((DataSetFSO.PAY_OUT_ON_INV_INRow)((DataRowView)e.Row.DataBoundItem).Row).PAY_DATE;
                decimal rate = FormHelper.GetRate((String) radDropDownListCurrency.SelectedText, payDate);

                try
                {
                    if (rate > 0)
                    {
                        e.Row.Cells["SUM_RUB"].Value = ((decimal)(e.Row.Cells["SUM_CUR"]).Value) * rate;
                    }
                }
                catch (InvalidCastException)
                {
                    //Если в пустую ячейку так ничего и не ввели
                }
            }
            else if (e.Column.Name == "SUM_RUB")
            {
                DateTime payDate = ((DataSetFSO.PAY_OUT_ON_INV_INRow)((DataRowView)e.Row.DataBoundItem).Row).PAY_DATE;
                decimal rate = FormHelper.GetRate((String) radDropDownListCurrency.SelectedText, payDate);

                try
                {
                    if (rate > 0)
                    {
                        e.Row.Cells["SUM_CUR"].Value = ((decimal)(e.Row.Cells["SUM_RUB"]).Value) / rate;
                    }
                }
                catch (InvalidCastException)
                {
                    //Если в пустую ячейку так ничего и не ввели
                }

            }
        }

        */
        //возвращает остаток счета
        private decimal GetRest()
        {
            return (_rowInvoiceIn.IsSUMNull() ? 0 : _rowInvoiceIn.SUM) - (from row in dataSetFSO1.PAY_OUT_ON_INV_IN select (row.IsSUM_CURNull() ? 0 : row.SUM_CUR)).Sum();
        }

        //Возвращает остаток определенного счета (из форм, где нельзя изменить данные влияющие на остаток)
        public static decimal GetRest(int InvID)
        {
            DataSetFSO.INVOICE_INRow invIntRow;
            DataSetFSO.PAY_OUT_ON_INV_INDataTable dt;
            Zvezda.FSO2.DB.DataSetFSOTableAdapters.INVOICE_INTableAdapter taInv = new Zvezda.FSO2.DB.DataSetFSOTableAdapters.INVOICE_INTableAdapter();
            Zvezda.FSO2.DB.DataSetFSOTableAdapters.PAY_OUT_ON_INV_INTableAdapter taPoI = new Zvezda.FSO2.DB.DataSetFSOTableAdapters.PAY_OUT_ON_INV_INTableAdapter();

            invIntRow = taInv.GetDataByID(InvID).FindByID(InvID);
            dt = taPoI.GetDataByInvInID(InvID);


            return (invIntRow.IsSUMNull() ? 0 : invIntRow.SUM) - (from row in dt select (row.IsSUM_CURNull() ? 0 : row.SUM_CUR)).Sum();
        }

        //Возвращает остаток без учета значения одного платежа
        public static decimal GetRestWithoutItem(int InvID, int? poiID)
        {
            DataSetFSO.INVOICE_INRow invIntRow;
            DataSetFSO.PAY_OUT_ON_INV_INDataTable dt;
            Zvezda.FSO2.DB.DataSetFSOTableAdapters.INVOICE_INTableAdapter taInv = new Zvezda.FSO2.DB.DataSetFSOTableAdapters.INVOICE_INTableAdapter();
            Zvezda.FSO2.DB.DataSetFSOTableAdapters.PAY_OUT_ON_INV_INTableAdapter taPoI = new Zvezda.FSO2.DB.DataSetFSOTableAdapters.PAY_OUT_ON_INV_INTableAdapter();

            decimal rest = 0;

            invIntRow = taInv.GetDataByID(InvID).FindByID(InvID);
            dt = taPoI.GetDataByInvInID(InvID);

            if(poiID != null)
            {
                rest = (invIntRow.IsSUMNull() ? 0 : invIntRow.SUM) - (from row in dt select ((row.IsSUM_CURNull() || row.ID == poiID) ? 0 : row.SUM_CUR)).Sum();
            }
            else
            {
                rest = (invIntRow.IsSUMNull() ? 0 : invIntRow.SUM) - (from row in dt select ((row.IsSUM_CURNull()) ? 0 : row.SUM_CUR)).Sum();
            }

            return rest;
        }

        private void radDateTimePickerPlanPaymentDate_Opened(object sender, EventArgs e)
        {
            if (radDateTimePickerPlanPaymentDate.Value == radDateTimePickerPlanPaymentDate.NullDate)
            {
                radDateTimePickerPlanPaymentDate.Value = DateTime.Now.Date;
            }
        }

    }
	public class MyAutoCompleteAppendHelper : AutoCompleteAppendHelper
	{
		public MyAutoCompleteAppendHelper(RadDropDownListElement elm)
			: base(elm)
		{
		}

		protected override bool DefaultCompare(RadListDataItem item)
		{
			return item.Text.Contains(base.FindString);
		}

	}
}
